package com.grj.parkingsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grj.parkingsystem.common.JwtUtil;
import com.grj.parkingsystem.entity.Coupon;
import com.grj.parkingsystem.entity.ParkingOrder;
import com.grj.parkingsystem.entity.User;
import com.grj.parkingsystem.mapper.UserMapper;
import com.grj.parkingsystem.service.CouponService;
import com.grj.parkingsystem.mapper.CouponMapper;
import com.grj.parkingsystem.service.ParkingOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

/**
* @author ganru
* @description 针对表【t_coupon(优惠券表)】的数据库操作Service实现
* @createDate 2025-05-16 16:51:44
*/
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon>
    implements CouponService{

    @Resource
    private CouponMapper couponMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ParkingOrderService parkingOrderService;

    @Resource
    private JwtUtil jwtUtil;

    @Override
    public List<Coupon> getAvailableCoupons(String token) {

        // 解析Token
        String username = jwtUtil.getUsernameFromToken(token);
        // 查询用户信息
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        Date now = new Date();
        return baseMapper.selectList(new QueryWrapper<Coupon>()
                .eq("user_id", user.getId())
                .eq("status", 0) // 0: 未使用
                .ge("valid_to", now)
                .le("valid_from", now));
    }

    @Override
    @Transactional
    public boolean useCoupon(String token, Long couponId, Long orderId) {

        // 解析Token
        String username = jwtUtil.getUsernameFromToken(token);
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));

        Coupon coupon = baseMapper.selectById(couponId);

        if(!coupon.getUserId().equals(user.getId())){
            return false;
        }

        if (coupon.getStatus() != 0) {
            return false;
        }

        // 检查优惠券有效期
        Date now = new Date();
        if (coupon.getValidFrom().after(now) || coupon.getValidTo().before(now)) {
            return false;
        }

        // 更新优惠券状态
        coupon.setStatus(1); // 1: 已使用
        boolean success = updateById(coupon);

        if (success) {
            // 应用优惠券到订单（此处简化处理，实际需根据订单状态等进行验证）
            ParkingOrder order = parkingOrderService.getById(orderId);
            if (order != null && order.getOrderStatus() == 0) {
                // 根据优惠券类型计算优惠金额
                if (coupon.getCouponType() == 0) { // 满减
                    if (order.getOriginalPrice().compareTo(coupon.getMinConsume()) >= 0) {
                        order.setDiscountAmount(coupon.getAmount());
                        order.setActualPrice(order.getOriginalPrice().subtract(coupon.getAmount()));
                    }
                } else if (coupon.getCouponType() == 1) { // 折扣
                    BigDecimal discountRate = coupon.getAmount().divide(new BigDecimal(10), 2, RoundingMode.HALF_UP);
                    order.setDiscountAmount(order.getOriginalPrice().multiply(discountRate));
                    order.setActualPrice(order.getOriginalPrice().subtract(order.getDiscountAmount()));
                }
                parkingOrderService.updateById(order);
            }
        }

        return success;
    }

    @Override
    public void receiveCoupon(String token, Long couponTemplateId) {
        Coupon coupon = new Coupon();
        coupon.setUserId(1L);
        coupon.setCouponType(0);
        coupon.setAmount(new BigDecimal("10"));
        coupon.setMinConsume(new BigDecimal("100"));
        coupon.setValidFrom(new Date());
        coupon.setValidTo(new Date());
        coupon.setStatus(0);
        coupon.setCreateTime(new Date());
        couponMapper.insert(coupon);
    }
}




